package palmtop.com.palmtop.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import net.grandcentrix.tray.AppPreferences;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import palmtop.com.palmtop.R;
import palmtop.com.palmtop.adapter.CustomMultipleChoiceView;
import palmtop.com.palmtop.event.MainSyncEvent;
import palmtop.com.palmtop.model.Task;
import palmtop.com.palmtop.model.Taskgrid;
import palmtop.com.palmtop.model.User;
import palmtop.com.palmtop.util.Config;
import palmtop.com.palmtop.util.FuncUtil;
import palmtop.com.palmtop.util.NetUtil;
import palmtop.com.palmtop.util.ToastUtil;

public class DisleadertaskActivity extends BaseActivity {

    @BindView(R.id.mtitle)
    TextView mtitle;
    @BindView(R.id.taskname)
    AwesomeTextView taskname;
    @BindView(R.id.taskaddress)
    AwesomeTextView taskaddress;
    /*@BindView(R.id.selectmapBtn)
    Button selectmapBtn;*/
    @BindView(R.id.longitude)
    AwesomeTextView longitude;
    @BindView(R.id.latitude)
    AwesomeTextView latitude;
    @BindView(R.id.taskcontent)
    AwesomeTextView taskcontent;
    @BindView(R.id.receivername)
    BootstrapEditText receivername;
    @BindView(R.id.receiveBtn)
    Button receiveBtn;
    @BindView(R.id.footBtn)
    Button footBtn;
    Taskgrid taskgrid;
    @BindView(R.id.zphoto1)
    ImageView zphoto1;
    @BindView(R.id.zphoto2)
    ImageView zphoto2;
    @BindView(R.id.zphoto3)
    ImageView zphoto3;
    @BindView(R.id.zphoto4)
    ImageView zphoto4;

    private ArrayList arrlist;

    boolean[] checkitem;
    private ArrayList<String> useridlist;
    Task task;
    String ssgrid = "";
    String gridname = "";
    // private SharedPreferences sharedPreferences;
    String userid = "";
    String name = "";
    ArrayList<User> userlist;
    String receiverid = "";
    Context context;

    private PopupWindow stationSelectDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_disleadertask, Config.toptitle, 1);
        MyApplication app = (MyApplication) getApplication();
        app.addActivityList(DisleadertaskActivity.this);
        ButterKnife.bind(this);

        initView();
    }



    private void initView() {

        mtitle.setText("下发任务");
        footBtn.setText("下发");
//        sharedPreferences = getSharedPreferences("user",Context.MODE_PRIVATE);
        AppPreferences appPreferences = new AppPreferences(DisleadertaskActivity.this);
        ssgrid = appPreferences.getString("ssgrid", "");
        gridname = appPreferences.getString("gridname", "");
        userid = appPreferences.getString("userid", "");
        name = appPreferences.getString("name", "");
        //urlarr = new ArrayList<String>();
        arrlist = new ArrayList<String>();
        useridlist = new ArrayList<String>();
        userlist = new ArrayList<User>();
        context = this;
        taskgrid = (Taskgrid) getIntent().getSerializableExtra("taskgrid");
        if (taskgrid != null) {
            taskname.setText(taskgrid.getTaskname());
            taskaddress.setText(taskgrid.getTaskaddress());
            longitude.setText(taskgrid.getLongitude());
            latitude.setText(taskgrid.getLatitude());
            taskcontent.setText(taskgrid.getTaskcontent());
            if (taskgrid.getPhoto1() != null && !taskgrid.getPhoto1().equals("")) {
                x.image().bind(zphoto1, Config.IMG_URL + taskgrid.getPhoto1());
                FuncUtil.clickShowBigPic(Config.IMG_URL + taskgrid.getPhoto1(), zphoto1, DisleadertaskActivity.this);
            }
            if (taskgrid.getPhoto2() != null && !taskgrid.getPhoto2().equals("")) {
                x.image().bind(zphoto2, Config.IMG_URL + taskgrid.getPhoto2());
                FuncUtil.clickShowBigPic(Config.IMG_URL + taskgrid.getPhoto2(), zphoto2, DisleadertaskActivity.this);
            }
            if (taskgrid.getPhoto3() != null && !taskgrid.getPhoto3().equals("")) {
                x.image().bind(zphoto3, Config.IMG_URL + taskgrid.getPhoto3());
                FuncUtil.clickShowBigPic(Config.IMG_URL + taskgrid.getPhoto3(), zphoto3, DisleadertaskActivity.this);
            }
            if (taskgrid.getPhoto4() != null && !taskgrid.getPhoto4().equals("")) {
                x.image().bind(zphoto4, Config.IMG_URL + taskgrid.getPhoto4());
                FuncUtil.clickShowBigPic(Config.IMG_URL + taskgrid.getPhoto4(), zphoto4, DisleadertaskActivity.this);
            }

        }
    }

    private void addUserid(String username) {
        RequestParams params = new RequestParams(Config.SERVER_URL + "sys/loginapi/getUserByName");
        params.addBodyParameter("name", username);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                Type listType = new TypeToken<ArrayList<User>>() {
                }.getType();
                ArrayList<User> list = gson.fromJson(result, listType);
                if (list.size() > 0) {
                    useridlist.add(String.valueOf(list.get(0).getId()));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });


    }

 /*   @OnClick(R.id.selectmapBtn)
    public void onSelectmapBtnClicked() {
        startActivityForResult(new Intent(DisleadertaskActivity.this, SelectPositionActivity.class), 5);
    }*/

/*    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 5) {
            String address = data.getExtras().getString("address");
            Double latitude1 = data.getExtras().getDouble("latitude");
            Double longitude1 = data.getExtras().getDouble("longitude");
            taskaddress.setText(address);
            latitude.setText(String.valueOf(latitude1));
            longitude.setText(String.valueOf(longitude1));
        }
    }*/


    @OnClick(R.id.receiveBtn)
    public void onReceiveBtnClicked1() {

        RequestParams params = new RequestParams(Config.SERVER_URL + "sys/loginapi/getListBySsgrid");
        params.addBodyParameter("ssgrid", ssgrid);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                Type listType = new TypeToken<ArrayList<User>>() {
                }.getType();
                ArrayList<User> list = gson.fromJson(result, listType);
                userlist = gson.fromJson(result, listType);
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        arrlist.add(list.get(i).getName());
                    }
                }

                ArrayList<String> usernameList = new ArrayList<String>();

                if (list.size() > 0) {
                    for (User user : list) {
                        usernameList.add(user.getName());
                    }
                }
                String[] arrs = new String[usernameList.size()];
                usernameList.toArray(arrs);
                showMutiChoiceDialog(arrs, receivername);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });




    }
    private void showMutiChoiceDialog(final String[] stationsMean, final BootstrapEditText textView){
        if(stationSelectDialog == null){
            LayoutInflater inflater = LayoutInflater.from(this);
            View view = inflater.inflate(R.layout.dialog_multiplechoice, null);
            CustomMultipleChoiceView mutipleChoiceView = (CustomMultipleChoiceView) view.findViewById(R.id.CustomMultipleChoiceView);
            mutipleChoiceView.setData(stationsMean, null);
//            mutipleChoiceView.selectAll();
            mutipleChoiceView.setTitle("选择接收人");
            stationSelectDialog = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
            mutipleChoiceView.setOnSelectedListener(new CustomMultipleChoiceView.onSelectedListener() {
                @Override
                public void onSelected(SparseBooleanArray sparseBooleanArray) {
                    stationSelectDialog.dismiss();
                    StringBuilder sb = new StringBuilder();
//                    unitidlist.clear();
                    receiverid = "";
                    for(int i=0; i<sparseBooleanArray.size(); i++){
                        if(sparseBooleanArray.get(i)){
                            sb.append(stationsMean[i] + ",");
//                            addUnitid(stationsMean[i]);
                            for (int j = 0; j < userlist.size(); j++) {
                                if (stationsMean[i].equals(userlist.get(j).getName())) {
                                    receiverid += userlist.get(i).getId() + ",";
                                    continue;
                                }
                            }
                        }

                    }
                    if(sb.length() > 0)
                        sb.deleteCharAt(sb.length()-1);
                    textView.setText(sb.toString());
                }
            });
        }
        stationSelectDialog.showAtLocation(getCurrentFocus(), Gravity.CENTER, 0, 0);
    }

    //@OnClick(R.id.receiveBtn)
    public void onReceiveBtnClicked() {
        RequestParams params = new RequestParams(Config.SERVER_URL + "sys/loginapi/getListBySsgrid");
        params.addBodyParameter("ssgrid", ssgrid);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                Type listType = new TypeToken<ArrayList<User>>() {
                }.getType();
                ArrayList<User> list = gson.fromJson(result, listType);
                userlist = gson.fromJson(result, listType);
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        arrlist.add(list.get(i).getName());
                    }
                }

                ArrayList<String> usernameList = new ArrayList<String>();

                if (list.size() > 0) {
                    for (User user : list) {
                        usernameList.add(user.getName());
                    }
                }
                final String[] userdata = new String[usernameList.size()];
                checkitem = new boolean[list.size()];
                for (int a = 0; a < usernameList.size(); a++) {
                    userdata[a] = usernameList.get(a);
                    checkitem[a] = false;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMultiChoiceItems(userdata, checkitem, new
                        DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                checkitem[which] = isChecked;
                            }
                        });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String text = "";
                        receiverid = "";
                        for (int a = 0; a < userdata.length; a++) {
                            if (checkitem[a]) {
                                text += userdata[a] + ",";
                                //addUserid(userdata[a]);
                                for (int i = 0; i < userlist.size(); i++) {
                                    if (userdata[a].equals(userlist.get(i).getName())) {
                                        receiverid += userlist.get(i).getId() + ",";

                                    }
                                }
                            }
                        }
                        receivername.setText(text);
                    }
                });
                builder.show();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    @OnClick(R.id.footBtn)
    public void onFootBtnClicked() {
        if(TextUtils.isEmpty(receivername.getText())){
            ToastUtil.show(this,"接收人不能为空");
            return;
        }
        RequestParams params = new RequestParams(Config.SERVER_URL + "taskgridapp/update");
        params.addBodyParameter("id", String.valueOf(taskgrid.getId()));
        params.addBodyParameter("orataskid", String.valueOf(taskgrid.getOrataskid()));
        params.addBodyParameter("taskname", taskgrid.getTaskname());//任务内容
        params.addBodyParameter("taskaddress", taskgrid.getTaskaddress());//任务地点
        params.addBodyParameter("taskcontent", taskgrid.getTaskcontent());//具体内容
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String date = sDateFormat.format(new Date());
        params.addBodyParameter("adddate", date);// 添加时间
        params.addBodyParameter("longitude", taskgrid.getLongitude());
        params.addBodyParameter("latitude", taskgrid.getLatitude());
        params.addBodyParameter("status", "2");
        params.addBodyParameter("receivername", String.valueOf(receivername.getText()));
        params.addBodyParameter("unitid", String.valueOf(taskgrid.getUnitid()));
        params.addBodyParameter("unitname", taskgrid.getUnitname());
        params.addBodyParameter("addusername", name);
        params.addBodyParameter("adduserid", userid);
        /*StringBuffer sb = new StringBuffer();
        if(useridlist!=null&&useridlist.size()>0){
            for (int i = 0; i < useridlist.size(); i++) {
                sb.append(useridlist.get(i));
                sb.append(",");
            }
        }*/

//        if(sb.length()>0){
        params.addBodyParameter("receiverid", receiverid);
        params.addBodyParameter("photo1", String.valueOf(taskgrid.getPhoto1()));
        params.addBodyParameter("photo2", String.valueOf(taskgrid.getPhoto2()));
        params.addBodyParameter("photo3", String.valueOf(taskgrid.getPhoto3()));
        params.addBodyParameter("photo4", String.valueOf(taskgrid.getPhoto4()));

//        }

        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result.equals("success")) {
                    ToastUtil.show(DisleadertaskActivity.this, "下发成功");
                    EventBus.getDefault().post(new MainSyncEvent());
//                    finish();
                    Intent i = new Intent();
                    i.setClass(context,Main2Activity.class);
                    startActivity(i);

                } else {
                    ToastUtil.show(DisleadertaskActivity.this, "提交失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });

    }
}
